/*
 * @Author: 吴世扬 18368095041@163.com
 * @Date: 2025-02-14 15:39:20
 * @LastEditors: 吴世扬 18368095041@163.com
 * @LastEditTime: 2025-02-21 16:00:55
 * @FilePath: /vue3-admin-server/src/services/redis.service.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Injectable } from '@nestjs/common';
import { Redis } from 'ioredis';

import { ACCESS_TOKEN_KEY, ACCESS_TOKEN_EXPIRES } from 'src/common/constants';

const redisClient = new Redis(
    process.env.REDIS_PORT ?? 6379,
    process.env.REDIS_HOST ?? 'localhost',
    {}
);

@Injectable()
export class RedisService {
    constructor() {}

    /**
     * 将Token存储在Redis的集合中，并设置过期时间
     * @param userId 用户ID
     * @param token Token字符串
     */
    async setToken(userId: number, token: string): Promise<number> {
        const key = `${ACCESS_TOKEN_KEY}:${userId}`;
        await redisClient.set(key, token);
        return await redisClient.expire(
            key,
            process.env.ACCESS_TOKEN_EXPIRES ?? ACCESS_TOKEN_EXPIRES
        );
    }

    /**
     * 删除token
     * @param userId 用户ID
     */
    async deleteToken(userId: number): Promise<number> {
        const key = `${ACCESS_TOKEN_KEY}:${userId}`;
        return await redisClient.srem(key);
    }

    /**
     * 从Redis中删除所有token
     */
    async deleteAllTokens(): Promise<void> {
        try {
            // 使用 KEYS 命令查找所有 token 相关的键
            const keys = await redisClient.keys(`${ACCESS_TOKEN_KEY}:*`);
            if (keys.length > 0) {
                // 删除所有找到的键
                await redisClient.del(keys);
            }
        } catch (error) {
            console.error('Error deleting all tokens:', error);
            throw error;
        }
    }
}
